package com.farm.farming.service.impl;

import com.alibaba.fastjson.JSON;
import com.farm.entity.PageResult;
import com.farm.farming.dao.Cust_menuMapper;
import com.farm.farming.pojo.Cust_menu;
import com.farm.farming.service.Cust_menuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@Transactional
public class Cust_menuServiceImpl implements Cust_menuService {

    @Autowired
    private Cust_menuMapper cust_menuMapper;

    @Override
    public int add(Cust_menu cust_menu) {

        cust_menuMapper.save(cust_menu);

        return 0;
    }

    @Override
    public int delete(Integer id) {
        //查询中间表有没有数据
        int count = cust_menuMapper.findTcustRoleMenuByMenuId(id);
        if (count!=0)
            throw new RuntimeException("删除菜单失败了");
        //删除菜单的数据
        cust_menuMapper.deleteById(id);
        return 1;
    }

    @Override
    public int update(Cust_menu cust_menu) {
        //把对象转换为map
        Map<String,Object> newmap = JSON.parseObject(JSON.toJSONString(cust_menu), Map.class);
        //根据id查询数据库转为对象转为map
        Cust_menu menu = cust_menuMapper.getOne(cust_menu.getId());
        Map<String,Object> oldmap = JSON.parseObject(JSON.toJSONString(menu), Map.class);
        //调用填充null值的方法,
        Cust_menu newMenu = this.copyColumnnullValue(newmap,oldmap);
        //修改方法
        cust_menuMapper.save(newMenu);
        return 1;
    }

private Cust_menu copyColumnnullValue(Map newmap,Map oldmap){
    Set<Map.Entry<String,Object>> set = oldmap.entrySet();
    for (Map.Entry<String, Object> entry : set) {
        if (newmap.get(entry.getKey())==null){
            newmap.put(entry.getKey(),oldmap.get(entry.getKey()));
        }
    }
    Cust_menu menu = JSON.parseObject(JSON.toJSONString(newmap), Cust_menu.class);
    return menu;
}

    @Override
    public List<Cust_menu> findAll() {
        return null;
    }

    @Override
    public PageResult<Cust_menu> findPage(Cust_menu cust_menu, Integer currentPage, Integer size) {
        //分页条件
        PageRequest pageRequest = PageRequest.of(currentPage, size);

        //封装查询的条件
        Example<Cust_menu> example = Example.of(cust_menu, ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains()));

        //分页条件查询
        Page<Cust_menu> all = cust_menuMapper.findAll(example, pageRequest);
        return new PageResult(all.getTotalElements(),all.getContent());
    }

    @Override
    public Cust_menu findById(Integer id) {

        return cust_menuMapper.getOne(id);

    }
}
